package com.banfan.almond.web.security;

import com.banfan.almond.base.global.SQLConf;
import com.banfan.almond.base.global.SysConf;
import com.banfan.almond.entity.entity.Admin;
import com.banfan.almond.entity.entity.Role;
import com.banfan.almond.web.service.AdminService;
import com.banfan.almond.web.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //get user
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.USER_NAME, username);
        queryWrapper.last(SysConf.LIMIT_ONE);
        Admin admin = adminService.getOne(queryWrapper);

        if (admin == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            //get role
            Role role1 = roleService.getById(admin.getRoleUid());

            //get authority
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role1.getRoleName());

            //create authority list
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            grantedAuthorities.add(simpleGrantedAuthority);

            return new SecurityUser(
                    admin.getUid(),
                    admin.getRoleUid(),
                    admin.getUsername(),
                    admin.getPassword(),
                    admin.getStatus() == 1,
                    grantedAuthorities
            );

        }
    }
}
